package com.learn.metrics.fun.jvm;

import cn.hutool.core.thread.ThreadUtil;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import com.sun.management.OperatingSystemMXBean;

import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author XuYang
 * @since 2025/2/19 11:21
 */
public class JvmStatisticsExample {

    public static void start(Integer interval) {
        MetricRegistry registry = new MetricRegistry();
        // GC收集器
        registry.registerAll("GC", new GarbageCollectorMetricSet());
        // 内存收集器
        registry.registerAll("Memory", new MemoryUsageGaugeSet());
        // 线程状态收集器
        registry.registerAll("ThreadStatus", new ThreadStatesGaugeSet());

        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        // JVM在系统中CPU使用率 -1: 表示不可用
        registry.register("jvm-cpu", (Gauge<Double>) osBean::getProcessCpuLoad);
        // 系统CPU使用率 【0-1.0】 0：表示所有CPU都空闲  1: 表示所有CPU都忙碌  -1: 表示不可用
        registry.register("system-cpu", (Gauge<Double>) osBean::getCpuLoad);
        // 总内存数(byte)
        registry.register("total-member-size", (Gauge<Long>) osBean::getTotalMemorySize);
        // 空闲内存数(byte)
        registry.register("free-member-size", (Gauge<Long>) osBean::getFreeMemorySize);

        // 打印统计信息
        ConsoleReporter.forRegistry(registry).build().start(interval, TimeUnit.SECONDS);

        ThreadUtil.sleep(10000);
    }
}
